﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class NodeRelationController : BaseController
    {
        /// <summary>
        /// nối hai nút với nhau
        /// </summary>
        /// <param name="nodeRelation"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("add_node_relation")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddNodeRelation(NodeRelationModel nodeRelation)
        {
            try
            {
                List<ValidationResult> outError;
                if (nodeRelation.IsValid(out outError))
                {
                    var dbNodeRelation = new NodeRelation()
                        {
                            FromNodeId = nodeRelation.FromNodeId,
                            ToNodeId = nodeRelation.ToNodeId,
                            Name = nodeRelation.Name,
                            CreatedAt = DateTime.Now,
                            UpdatedAt = DateTime.Now,
                            FlowId = nodeRelation.FlowId
                        };
                    unitOfWork.NodeRelationRepository.Insert(dbNodeRelation);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                }

            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                throw;
            }
        }

        /// <summary>
        /// Xóa một quan hệ nút trong luồng
        /// </summary>
        /// <param name="FromNodeId"></param>
        /// <param name="ToNodeId"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("remove_node_relation")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult RemoveNodeRelation(int? FromNodeId, int? ToNodeId)
        {
            if(FromNodeId== null || ToNodeId==null)
            {
                return Json(SimplyResponse.Response200());
            }
            try
            {
                unitOfWork.NodeRelationRepository.Delete((int)FromNodeId,(int)ToNodeId);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }
    }
}
